// Protocol Buffers for GWT
// Copyright 2008 Google Inc.  All rights reserved.
// Copyright 2010 Thomas Broyer  All rights reserved.
// http://code.google.com/p/protobuf-gwt/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

package com.google.protobuf;

import java.io.FilterOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * @author t.broyer@ltgt.net Thomas Broyer
 * Based on the initial work of:
 * @author crazybob@google.com Bob Lee
 * @author kenton@google.com Kenton Varda
 */
public final class ByteString {
  private static void appendBytes(StringBuilder sb, byte[] bytes, int off, int len) {
    for (int i = off, end = off + len; i < end; i++) {
      sb.append((char) (bytes[i] & 0xff));
    }
  }
  
  public static final class Output extends FilterOutputStream {

    private StringBuilder sb;
    
    private Output() {
      super(null);
    }
    
    public void close() {
    }
    
    public void flush() {
    }
    
    public ByteString toByteString() {
      return new ByteString(sb.toString());
    }
    
    public void write(byte[] b) throws IOException {
      write(b, 0, b.length);
    }
    
    public void write(byte[] b, int off, int len) {
      appendBytes(sb, b, off, len);
    }
    
    public void write(int b) {
      sb.append((char) ((byte) b));
    }
  }
  
  // make it accessible to ByteString_CustomFieldSerializer
  final String bytes;

  // make it accessible to Internal.bytesDefaultValue and ByteString_CustomFieldSerializer
  ByteString(String bytes) {
    this.bytes = bytes;
  }

  public byte byteAt(final int index) {
    return (byte) bytes.charAt(index);
  }

  public int size() {
    return bytes.length();
  }

  public boolean isEmpty() {
    return bytes.length() == 0;
  }

  public static final ByteString EMPTY = new ByteString("");

  public static ByteString copyFrom(final byte[] bytes, final int offset,
                                    final int size) {
    StringBuilder sb = new StringBuilder(size);
    appendBytes(sb, bytes, offset, size);
    return new ByteString(sb.toString());
  }

  public static ByteString copyFrom(final byte[] bytes) {
    return copyFrom(bytes, 0, bytes.length);
  }

  public static native ByteString copyFromUtf8(final String text) /*-{
    var bytes = unescape(encodeURIComponent(text));
    return new @com.google.protobuf.ByteString::new(Ljava/lang/String;)(bytes);
  }-*/;

  public static ByteString copyFrom(List<ByteString> list) {
    if (list.size() == 0) {
      return EMPTY;
    } else if (list.size() == 1) {
      return list.get(0);
    }

    StringBuilder sb = new StringBuilder();
    for (ByteString bs : list) {
      sb.append(bs.bytes);
    }
    return new ByteString(sb.toString());
  }

  public void copyTo(final byte[] target, final int offset) {
    copyTo(target, 0, offset, size());
  }

  public void copyTo(final byte[] target, final int sourceOffset,
                     final int targetOffset,
      final int size) {
    if (sourceOffset < 0 || targetOffset < 0 || size < 0 || sourceOffset + size > size() || targetOffset + size > target.length) {
      throw new IndexOutOfBoundsException();
    }
    for (int i = sourceOffset, j = targetOffset, l = sourceOffset + size; i < l; i++, j++) {
      target[j] = byteAt(i);
    }
  }

  /**
   * Copies bytes to a {@code byte[]}.
   */
  public byte[] toByteArray() {
    final int size = size();
    final byte[] copy = new byte[size];
    for (int i = 0; i < size; i++) {
      copy[i] = byteAt(i);
    }
    return copy;
  }

  public String toStringUtf8() {
    return Internal.stringDefaultValue(bytes);
  }

  @Override
  public boolean equals(final Object o) {
    if (o == this) {
      return true;
    }

    if (!(o instanceof ByteString)) {
      return false;
    }

    final ByteString other = (ByteString) o;
    return bytes.equals(other.bytes);
  }

  @Override
  public int hashCode() {
    return bytes.hashCode();
  }
  
  @Override
  public native String toString() /*-{
    return escape(this.@com.google.protobuf.ByteString::bytes);
  }-*/;
}
